package com.shujia.scala

import scala.io.Source

object Demo27Match {
  def main(args: Array[String]): Unit = {

    /**
      * 模式匹配
      * java 模式匹配可以匹配  基本数据类型，String   枚举
      *
      *
      * scala的模式匹配可以匹配，基本数据类型，字符串，枚举， 类型匹配， 样例类
      *
      */

    //1、匹配基本数据类型

    val i = 100

    /**
      * match： 按照循序匹配，只匹配成功一次
      *
      */

    i match {
      case 100 => println("100")
      case 200 => println("2000")
      //匹配其它情况
      case _ => println("其它")
    }

    //模式匹配可以友返回值
    //d对变量i j奇数加一，偶数乘2
    val j: Int = i % 2 match {
      case 1 => i + 1
      case 0 => i * 2
    }

    println(j)

    //2、匹配类型

    var str: Any = 12312.0

    //需要匹配的类型只能是变量类型的子类型
    str match {
      case s: String => println(s"字符串类型:$s")
      case i: Int => println(s"Int类型：$i")
      case _ => println(s"其它类型：$str")
    }


    //匹配样例类
    case class User(id: String, name: String)

    val user = User("004", "张三")


    user match {
      case User("001", "张三") => println("张三")
      case User("002", "李四") => println("李四")
      case User("003", "王五") => println("王五")
      case i: User => println(i)
      case _ => println("其它")
    }


    /**
      * 应用
      *
      */

    val list = List(("001", "张三", 23), ("002", "李四", 24), ("003", "王五", 25))

    val list2: List[(String, String, Int)] = list.map(kv => {
      val id: String = kv._1
      val name: String = kv._2
      val age: Int = kv._3
      (id, name, age + 1)
    })

    list2.foreach(println)

    //简写
    val list3: List[(String, String, Int)] = list.map {
      case (id: String, name: String, age: Int) => {
        (id, name, age + 1)
      }
    }

    list3.foreach(println)

    println("=" * 100)

    val students: List[String] = Source.fromFile("data/students.txt").getLines().toList

    val list4: List[Array[String]] = students.map(student => student.split(","))

    //匹配数组
    val clazzAndAge: List[(String, String)] = list4.map {
      case Array(id: String, name: String, age: String, gender: String, clazz: String) => {

        (clazz, age)
      }
    }

    clazzAndAge.foreach(println)

  }

}
